#include "baidu_official_client.h"
#include <QDebug>
#include <QTimer>
#include <map>
#include <string>

// 在实现文件中包含完整的SDK
#include "../../resources/aip-cpp-sdk-4.16.7/speech.h"

BaiduOfficialClient::BaiduOfficialClient(QObject *parent)
    : QObject(parent)
    , m_initialized(false)
    , m_pendingRate(16000)
    , m_processTimer(new QTimer(this))
{
    // 设置单次触发的定时器，用于异步处理
    m_processTimer->setSingleShot(true);
    connect(m_processTimer, &QTimer::timeout, this, &BaiduOfficialClient::processRecognition);
}

BaiduOfficialClient::~BaiduOfficialClient()
{
}

bool BaiduOfficialClient::initialize(const QString &appId, const QString &apiKey, const QString &secretKey)
{
    m_appId = appId;
    m_apiKey = apiKey;
    m_secretKey = secretKey;
    
    qDebug() << "初始化百度官方语音识别客户端...";
    qDebug() << "AppID:" << m_appId;
    qDebug() << "API Key:" << m_apiKey.left(8) + "...";
    
    try {
        // 创建百度官方SDK客户端
        m_speechClient = std::make_unique<aip::Speech>(
            m_appId.toStdString(),
            m_apiKey.toStdString(),
            m_secretKey.toStdString()
        );
        
        // 设置超时时间
        m_speechClient->setConnectionTimeoutInMillis(10000); // 10秒连接超时
        m_speechClient->setSocketTimeoutInMillis(30000);     // 30秒读取超时
        
        m_initialized = true;
        qDebug() << "百度官方语音识别客户端初始化成功";
        return true;
        
    } catch (const std::exception &e) {
        qWarning() << "百度官方语音识别客户端初始化失败:" << e.what();
        m_initialized = false;
        return false;
    }
}

void BaiduOfficialClient::recognizeAudio(const QByteArray &audioData, const QString &format, int rate)
{
    if (!m_initialized || !m_speechClient) {
        emit recognitionError("客户端未初始化");
        return;
    }
    
    // 检查音频数据大小
    if (audioData.size() > 1200000) {
        emit recognitionError("音频数据过大，请缩短录音时间");
        return;
    }
    
    if (audioData.size() < 1000) {
        emit recognitionError("音频数据过小，请重新录音");
        return;
    }
    
    qDebug() << "开始百度官方SDK语音识别，音频大小:" << audioData.size() << "字节";
    
    // 保存待处理的数据
    m_pendingAudioData = audioData;
    m_pendingFormat = format;
    m_pendingRate = rate;
    
    // 异步处理，避免阻塞UI线程
    m_processTimer->start(10); // 10ms后开始处理
}

void BaiduOfficialClient::processRecognition()
{
    if (!m_initialized || !m_speechClient || m_pendingAudioData.isEmpty()) {
        return;
    }
    
    try {
        qDebug() << "使用百度官方SDK进行语音识别...";
        
        // 准备音频数据
        std::string audioDataStr(m_pendingAudioData.constData(), m_pendingAudioData.size());
        
        // 设置识别参数
        std::map<std::string, std::string> options;
        options["dev_pid"] = "1537"; // 普通话识别
        
        // 调用百度官方SDK进行识别
        Json::Value result = m_speechClient->recognize(
            audioDataStr,
            m_pendingFormat.toStdString(),
            m_pendingRate,
            options
        );
        
        qDebug() << "百度官方SDK识别完成";
        
        // 解析结果
        if (result.isMember("err_no")) {
            int errNo = result["err_no"].asInt();
            if (errNo == 0) {
                // 识别成功
                if (result.isMember("result") && result["result"].isArray() && !result["result"].empty()) {
                    std::string recognizedText = result["result"][0].asString();
                    QString text = QString::fromStdString(recognizedText);
                    qDebug() << "百度官方SDK识别成功:" << text;
                    emit recognitionResult(text);
                } else {
                    emit recognitionError("识别结果为空");
                }
            } else {
                // 识别失败
                std::string errMsg = result.isMember("err_msg") ? result["err_msg"].asString() : "未知错误";
                QString error = QString("识别失败[%1]: %2").arg(errNo).arg(QString::fromStdString(errMsg));
                qWarning() << "百度官方SDK识别失败:" << error;
                emit recognitionError(error);
            }
        } else if (result.isMember("curl_error_code")) {
            // 网络错误
            int curlError = result["curl_error_code"].asInt();
            QString error = QString("网络请求失败，错误码: %1").arg(curlError);
            qWarning() << "百度官方SDK网络错误:" << error;
            emit recognitionError(error);
        } else {
            emit recognitionError("未知的响应格式");
        }
        
    } catch (const std::exception &e) {
        QString error = QString("百度官方SDK异常: %1").arg(e.what());
        qWarning() << error;
        emit recognitionError(error);
    }
    
    // 清空待处理数据
    m_pendingAudioData.clear();
}

void BaiduOfficialClient::stopRecognition()
{
    qDebug() << "停止百度官方SDK语音识别";
    
    // 停止处理定时器
    if (m_processTimer) {
        m_processTimer->stop();
    }
    
    // 清空待处理的音频数据
    m_pendingAudioData.clear();
} 